<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\Device\JiejieApi;
use App\Models\XcDevice;
use App\Models\XcUser;
use App\Models\XcSiteWashmode;
use App\Models\XcFactory;
use App\Http\Requests\DeviceRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;



/**
 * Created by tommy on 2023/11/09
 * 
 * 后台设备管理控制层
 * 主要用来添加新设备，远程启动机器，生成设备的小程序码。
 * 
 *
 */
class DeviceController extends Controller
{

	/**
	 * 设备列表视图
	 * 
	 */ 
	public function index(Request $request)
	{
		
		$factory = XcFactory::get();
		return View::make('admin.device.index',compact('factory'));
	}

	/**
	 * 获得设备列表数据
	 * @param  int  factoryid  厂商ID，目前两家，捷洁/嗨卡
     * @return \Illuminate\Contracts\View\View
	 * 
	 */ 
	public function data(Request $request)
	{
		$factoryid = $request->get("factoryid");
		$xcdevice = XcDevice::query();
		if ($factoryid > 0 ) $xcdevice->where("factoryid", $factoryid);
		$res = $xcdevice->with(["factory","site"])->paginate($request->get('limit',10));

		$data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
	}

	/**
	 * 新建设备视图
	 * 
	 */ 
	public function create(Request $request)
	{
		
		$factory = XcFactory::get();
		return view("admin.device.create",compact('factory'));
	}

	/**
	 * 保存设备数据 
	 *
	 */ 
	public function store(DeviceRequest $request)
	{
		
		$user = Auth::guard('web')->user();
        $data = $request->validated();
        $factory = XcFactory::where("id", $data['factory_id'])->first();
        $prefix = $factory->ci??"";
        $data['open_sn']  = $prefix.rand(10000000, 99999999);
        $data['cuser_id'] = $user->id;

        //dd($data);
        try{
            $device = XcDevice::create($data);
            //return Redirect::to(URL::route('admin.site',['id' => $data['renter_id']]))->with(['success'=>'创建成功']);
            return '<script>window.parent.layer.closeAll();
                        window.parent.layer.msg("创建成功");
                        window.parent.layui.table.reload("dataTable");</script>';
        }catch (\Exception $exception){
            return Redirect::back()->withErrors($exception->getMessage());
        }
	}

	/**
	 * 编辑设备视图
	 *
	 */
	public function edit(Request $request)
	{
		$id = $request->get("id");
		$device = XcDevice::where("id", $id)->first();
		$factory = XcFactory::get();
		return view("admin.device.edit", compact("device","factory"));
	}

	/**
	 * 更新设备数据 
	 *
	 */
	public function update(DeviceRequest $request)
	{
		$id 	= $request->get("id");
		$data 	= $request->validated();

		try{
			XcDevice::where("id", $id)->update($data);
			return '<script>window.parent.layer.closeAll();
	                        window.parent.layer.msg("修改成功");
	                        window.parent.layui.table.reload("dataTable");</script>';
        }catch (\Exception $exception){
            return Redirect::back()->withErrors($exception->getMessage());
        }
	}

	/**
	 * 删除设备 
	 *
	 */
	public function destory(Request $request)
	{
		
		return Response::json($data);
	}

	/**
	 * 后台启动机器
	 * 
	 * 
	 */ 
	public function start(Request $request)
	{
		$res 		= ['code' => -1,'msg' => 'failed'];
        $open_sn 	= $request->get("open_sn");//设备外部编号 
        $factory_api = $this->getfactoryclass($open_sn);
        $xcdevice  = XcDevice::where("open_sn", $open_sn)->first();

		if (substr($open_sn, 0, 2) == "jj")
        {
        	$order_sn 	= OrderSN("JJ");
			/*捷洁启动接口
	        $apires = $factory_api->Start($xcdevice->device_no, $order_sn, 3);
	        */
	        //模拟启动成功接口
	        $apires['result'] = 1;
	        $apires['err_msg'] = '';

	        if ($apires['result'] == 1){
	        	$res['code'] = 0;
	        	$res['msg']  = '启动成功';
	        }else{
	        	$res['code'] = -1;
	        	$res['msg']  = '启动失败';
	        }
	    }

	    return response()->json($res);
	}

	/**
	 * 生成设备的小程序码，后续所有设备全部采用新的二维码进行访问。
	 * 
	 * @param string $open_sn 设备对外的编号
     * @return \Illuminate\Http\JsonResponse
	 */ 
	public function xcxqrcode(Request $request)
    {
    	//dd($_SERVER);
    	$open_sn 		= $request->get("open_sn");
    	$device 		= XcDevice::where("open_sn", $open_sn)->first();
    	//如果小程序二维码有保存,则直接返回
    	if (isset($device->imgurl) && !empty($device->imgurl)){
    		$urlarra = ['imgurl'=>$device->imgurl];
    		return response()->json(['code' => 0, 'msg' => 'success', 'data' => $urlarra]);
    	}
    	//查询redis是否缓存过access_token, 有则直接使用，如果没有，则请求微信接口
    	$access_token = Redis::get('XICHE_MAKE_QRCODE_ACCESS_TOKEN');
    	
    	if (!$access_token){
    		
	        $appid      = 'wx2e9856682e2666f8';
	        $secret     = '4869dd16c125c8bc98f8c352fb9352de';
	        $url        = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
	        $result     = file_get_contents($url);
	        $html       = json_decode($result,true);
	        Log::info($html);
	        $access_token = $html['access_token'];
	        $expires_in   = $html['expires_in'];
	        Redis::setex('XICHE_MAKE_QRCODE_ACCESS_TOKEN', $expires_in, $access_token);
    	}
    	
        //dd($access_token);
        //$access_token ='79_a2AdC0bBM1i8jlbkIYxWMhNYmPFwod35Qt8C8IbAryVv-4jCD3BlF0ilc6fbUolmeAGCl-egA-hw6akCF4YebSBJV4W7XZC9hLtIsdeWYnc_XT-CxdH0ZYhFHokPSNfACAKNI';

        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $param = [
                'scene'         => 'open_sn--'.$open_sn,
                'page'          => 'packageA/pages/payment/index',
                'width'         => 500,
                //'env_version'   => 'develop',//生成开发环境
                'auto_color'    => true,
                //'line_color'	=> '{"r":"255","g":"165","b":"79"}'
                ];

        $result = SendPostCmd($url,json_encode($param));//请求微信接口
        $errcode = json_decode($result,true)['errcode'];
        $errmsg = json_decode($result,true)['errmsg'];
        //dd($result);
        if($errcode) {
            return response()->json(['code'=> -1,'msg' => 'failed', 'data' =>$errcode]); 
        }
        $filename = $open_sn.'.png';
        $file = $_SERVER['DOCUMENT_ROOT'].'/xcxqrcode/'.$filename;
        $res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件
        if($res===false){
            return response()->json(['code' => -1, 'msg' => '生成二维码失败']);
        }else{
        	$urlarra = ['imgurl' => 'https://'.$_SERVER['HTTP_HOST'].'/xcxqrcode/'.$filename];
        	XcDevice::where("open_sn", $open_sn)->update($urlarra);
            return response()->json(['code' => 0, 'msg' => 'success', 'data' => $urlarra]);
        }
    }

    /**
     * 此主要是为后面扩展预留，目前只有捷洁，后面如果有嗨卡的话，再进行迭代
     * 
     * @param stirng $str jj/hk
     * @return Object
     * 
     */ 
	private function getfactoryclass( $str = 'jj')
    {
        $factory_api = [];
        $prefix  = substr($str, 0, 2);
        //如果是捷洁的设备
        if ($prefix == "jj"){
            $factory_api = JiejieApi::getInstance();
        }else if ($prefix == "hk"){//如果是嗨卡

        }
        return $factory_api;
    }

}